/*
 * Copyright (c) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "ola_pal_store.h"
#include "utils_file.h"
#include "securec.h"

#define FILENAME_MAX_LEN    32
#define FILENAME_PREFIX     "ola_store_"

static int GetFullPath(char *path, unsigned int len, const char *key)
{
    if (snprintf_s(path, len, len - 1, "%s%s", FILENAME_PREFIX, key) <= 0) {
        return -1;
    }
    return 0;
}

int OlaStoreInit(void)
{
    return 0;
}

int OlaStoreDeinit(void)
{
    return 0;
}

int OlaStoreSet(const char *key, const unsigned char *value, unsigned int len)
{
    if ((key == NULL) || (value == NULL) || (len == 0)) {
        return -1;
    }

    char path[FILENAME_MAX_LEN] = { 0 };
    if (GetFullPath(path, sizeof(path), key) != 0) {
        return -1;
    }

    int fd = UtilsFileOpen(path, O_RDWR_FS | O_CREAT_FS | O_TRUNC_FS, 0);
    if (fd == -1) {
        return -1;
    }

    if (UtilsFileWrite(fd, (const char *)value, len) == -1) {
        UtilsFileClose(fd);
        return -1;
    }

    UtilsFileClose(fd);
    return 0;
}

int OlaStoreGet(const char *key, unsigned char *value, unsigned int *len)
{
    if ((key == NULL) || (value == NULL) || (len == NULL) || (*len == 0)) {
        return -1;
    }

    char path[FILENAME_MAX_LEN] = { 0 };
    if (GetFullPath(path, sizeof(path), key) != 0) {
        return -1;
    }

    int fd = UtilsFileOpen(path, O_RDWR_FS, 0);
    if (fd == -1) {
        return -1;
    }

    if (UtilsFileSeek(fd, 0, SEEK_SET_FS) == -1) {
        UtilsFileClose(fd);
        return -1;
    }

    int readLen = UtilsFileRead(fd, (char *)value, *len);
    UtilsFileClose(fd);
    if (readLen < 0) {
        return -1;
    }

    *len = readLen;
    return 0;
}

int OlaStoreDel(const char *key)
{
    if (key == NULL) {
        return -1;
    }

    char path[FILENAME_MAX_LEN] = { 0 };
    if (GetFullPath(path, sizeof(path), key) != 0) {
        return -1;
    }

    if (UtilsFileDelete(path) != 0) {
        return -1;
    }
    return 0;
}
